package com.lzm.ydpt.module.mall.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.baseadapter.lv.LvCommonAdapter;
import com.byt.framlib.baseadapter.lv.LvViewHolder;
import com.byt.framlib.basemvp.boby.FormBodys;
import com.byt.framlib.commonutils.CopyUtils;
import com.byt.framlib.commonutils.TimeUtil;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.NormalTitleBar;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.byt.framlib.commonwidget.onclicktwo.AntiShake;
import com.byt.framlib.commonwidget.selectordialog.dialog.DialogOnClickListener;
import com.byt.framlib.commonwidget.selectordialog.dialog.NormalAlertDialog;
import com.lzm.ydpt.BaseColor;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.LogisticsDetails;
import com.lzm.ydpt.entity.mall.LogisticsList;
import com.lzm.ydpt.mvp.contract.LogisticsDetailsContract;
import com.lzm.ydpt.mvp.presenterimpl.LogisticsDetailsPresenterImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 类名称：  LogisticsDetailsActivity
 * 类描述：  物流详情界面
 */
public class LogisticsDetailsActivity extends BaseActivity<LogisticsDetailsPresenterImpl> implements LogisticsDetailsContract.View {

    public static final String INP_ORDER_LOGISTICS_NUM = "order_logistics_num";
    public static final String INP_ORDER_REFUND_ID = "order_refund_id";
    public static final String INP_LOGISTICS_TYPE = "logistics_type";

    @BindView(R.id.ntb_logistics_details)
    NormalTitleBar ntb_logistics_details;
    @BindView(R.id.ltp_logistics_details)
    LoadingTip tip_logistics_details;
    @BindView(R.id.ll_show_logistic)
    LinearLayout ll_show_logistic;
    @BindView(R.id.tv_logistics_company)
    TextView tv_logistics_company;
    @BindView(R.id.tv_logistics_num)
    TextView tv_logistics_num;
    @BindView(R.id.lv_logistics_details)
    ListView lv_logistics_details;
    private LvCommonAdapter<LogisticsList> adapter = null;
    private List<LogisticsList> logisticsLists = new ArrayList<>();

    private LogisticsDetails mDetails;
    private long order_id;

    private NormalAlertDialog normalAlertDialog;
    private long order_refund_id;
    private int logicType = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_logistics_details;
    }

    @Override
    public LogisticsDetailsPresenterImpl initPreData() {
        return new LogisticsDetailsPresenterImpl(this);
    }

    @Override
    public void initView() {
        order_id = getIntent().getLongExtra(INP_ORDER_LOGISTICS_NUM, 0L);
        order_refund_id = getIntent().getLongExtra(INP_ORDER_REFUND_ID, 0L);
        logicType = getIntent().getIntExtra(INP_LOGISTICS_TYPE, 0);
        ntb_logistics_details.setTitleText("物流信息");
        if (logicType == 1) {
            ntb_logistics_details.setRightTitle("查看订单");
            ntb_logistics_details.setRightTitleVisibility(true);
            ntb_logistics_details.setOnRightTextListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle detailsBundle = new Bundle();
                    detailsBundle.putLong(Constants.INP_ORDER_ID, order_id);
                    openActivity(MallOrderDetailsActivity.class, detailsBundle);
                }
            });
        }
        ntb_logistics_details.setOnBackListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        tip_logistics_details.setLoadingTip(LoadingTip.LoadStatus.loading);
        tip_logistics_details.setLinearLayoutBgColor(Color.WHITE);
        initAdapter();
        fetchData();
    }

    private void initAdapter() {
        adapter = new LvCommonAdapter<LogisticsList>(mBContext, logisticsLists, R.layout.item_logistics_lists_data_lv) {
            @Override
            protected void convert(LvViewHolder viewHolder, LogisticsList item, int position) {
                if (!TextUtils.isEmpty(item.getDatetime())) {
                    Date date = TimeUtil.getDateByFormat(item.getDatetime(), TimeUtil.dateFormatYMDHMS);
                    String time = TimeUtil.formatData("MM-dd\nHH:mm", date.getTime() / 1000);
                    viewHolder.setText(R.id.tv_logistics_list_time, time);
                    viewHolder.setVisible(R.id.tv_logistics_list_time, true);
                } else {
                    viewHolder.setVisible(R.id.tv_logistics_list_time, false);
                }
                TextView tv_logistics_list_remark = viewHolder.getView(R.id.tv_logistics_list_remark);
                if (position == 0) {
                    viewHolder.setTextColor(R.id.tv_logistics_list_remark, BaseColor.color_333333);
                    viewHolder.setSelected(R.id.view_logistics_list_dot, true);
                } else {
                    viewHolder.setSelected(R.id.view_logistics_list_dot, false);
                    viewHolder.setTextColor(R.id.tv_logistics_list_remark, BaseColor.color_999999);
                }
                tv_logistics_list_remark.setText(formatPhoneNumber(tv_logistics_list_remark, item.getRemark()));
            }
        };
        lv_logistics_details.setAdapter(adapter);
    }

    private void fetchData() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        formBodys.add("order_id", order_id);
        if (order_refund_id > 0) {
            formBodys.add("order_refund_id", order_refund_id);
            formBodys.add("type", 2);
        } else {
            formBodys.add("type", 1);
        }
        mPresenter.onProductLogistics(formBodys.build());
    }

    @OnClick({R.id.tv_copy_num})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_copy_num:
                CopyUtils.copyStringToClipBoard(this, mDetails.getExpress_sn());
                break;
        }
    }


    private static final String PATTERN_PHONE = "((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}";
    private static final String SCHEME_TEL = "tel:";

    /**
     * 格式化TextView的显示格式，识别手机号
     *
     * @param textView
     * @param source
     * @return
     */
    private SpannableStringBuilder formatPhoneNumber(TextView textView, String source) {
        // 若要部分 SpannableString 可点击，需要如下设置
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        // 将要格式化的 String 构建成一个 SpannableStringBuilder
        SpannableStringBuilder value = new SpannableStringBuilder(source);
        // 使用正则表达式匹配电话
        Linkify.addLinks(value, Pattern.compile(PATTERN_PHONE), SCHEME_TEL);
        // 获取上面到所有 addLinks 后的匹配部分(这里一个匹配项被封装成了一个 URLSpan 对象)
        URLSpan[] urlSpans = value.getSpans(0, value.length(), URLSpan.class);
        for (final URLSpan urlSpan : urlSpans) {
            if (urlSpan.getURL().startsWith(SCHEME_TEL)) {
                int start = value.getSpanStart(urlSpan);
                int end = value.getSpanEnd(urlSpan);
                value.removeSpan(urlSpan);
                value.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        String phone = urlSpan.getURL().replace(SCHEME_TEL, "");
                        normalAlertDialog = new NormalAlertDialog.Builder(mBContext)
                                .setButtonTextSize(14)
                                .setTitleVisible(true)
                                .setTitleText("温馨提示")
                                .setTitleTextSize(16)
                                .setContentText("是否拨打电话:" + phone + "?")
                                .setContentTextSize(14)
                                .setContentTextColor(R.color.title_color)
                                .setOnclickListener(new DialogOnClickListener() {
                                    @Override
                                    public void clickLeftButton(View view) {
                                    }

                                    @Override
                                    public void clickRightButton(View view) {
                                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                    }
                                }).build();
                        normalAlertDialog.show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(BaseColor.color_333333);
                        ds.setUnderlineText(true);
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return value;
    }


    @Override
    public void onLogisticsDetails(LogisticsDetails data) {
        tip_logistics_details.setLoadingTip(LoadingTip.LoadStatus.finish);
        this.mDetails = data;
        if (data != null) {
            ll_show_logistic.setVisibility(View.VISIBLE);
            tv_logistics_company.setText("物流公司:" + data.getExpress_company());
            tv_logistics_num.setText("物流单号：" + data.getExpress_sn());
            logisticsLists.clear();
            logisticsLists.addAll(data.getList());
            adapter.notifyDataSetChanged();
        } else {
            tip_logistics_details.setLoadingTip(LoadingTip.LoadStatus.empty);
            tip_logistics_details.setTips("该订单暂无物流");
        }

    }

    @Override
    public void showMessage(String message, String method) {

    }

    @Override
    public void showErrorView(String msg) {
        showErrorView(msg, tip_logistics_details);
        tip_logistics_details.setOnReloadListener(view -> {
            tip_logistics_details.setLoadingTip(LoadingTip.LoadStatus.loading);
            fetchData();
        });
    }
}